import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import(/* webpackChunkName: "home" */ '../views/home/Home.vue')
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import(/* webpackChunkName: "login" */ '../views/login/Login.vue'),
    beforeEnter: (to, from, next) => {
      // 只有访问Login页面之前才会执行次函数
      const { isLogin } = localStorage // 从本地存储中取isLogin
      // 如果登录，就跳到首页页面;否则跳转到登录页面
      isLogin ? next({ name: 'Home' }) : next()
    }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import(/* webpackChunkName: "register" */ '../views/register/Register.vue'),
    beforeEnter: (to, from, next) => {
      const { isLogin } = localStorage
      isLogin ? next({ name: 'Home' }) : next()
    }
  },
  {
    path: '/shop/:id',
    name: 'Shop',
    component: () => import(/* webpackChunkName: "shop" */ '../views/shop/Shop.vue')
  },
  {
    path: '/cartList',
    name: 'CartList',
    component: () => import(/* webpackChunkName: "cartList" */ '../views/cartList/CartList.vue')
  },
  {
    path: '/orderList',
    name: 'OrderList',
    component: () => import(/* webpackChunkName: "orderList" */ '../views/orderList/OrderList.vue')
  },
  {
    path: '/orderConfirmation/:shopId',
    name: 'OrderConfirmation',
    component: () =>
      import(
        /* webpackChunkName: "orderConfirmation" */ '../views/orderConfirmation/OrderConfirmation.vue'
      )
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})
// beforeEach:全局，每次做路由跳转之前都会执行这个操作。
router.beforeEach((to, from, next) => {
  // to and from are Route Object,
  // to:跳转的时候想要跳转的页面的信息
  // from :指从哪里跳过来的信息
  // next() must be called to resolve the hook}
  // 中间件继续执行的方法

  // 从本地存储中取isLogin
  const { isLogin } = localStorage

  console.log(to, from)
  /** 判断是否登录 */
  // 必须双循环，才能防止死循环
  // 如果没有登录，就跳到登录页面
  const { name } = to
  const isLoginOrRegister = name === 'Login' || name === 'Register'
  isLogin || isLoginOrRegister ? next() : next({ name: 'Login' })
})
export default router
